package single_list;

// 1、无头单向非循环链表实现
public class SingleLinkedList {
    private ListNode head;
    //头插法
    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;
    }

    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if(head == null) {
            head = node;
            return;
        }
        ListNode cur = head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
    }
    private boolean isIndexOutInAdd(int index) {
        return index < 0 || index > size();
    }
    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index, int data) {
        if(isIndexOutInAdd(index)) {
            return false;
        }

        ListNode node = new ListNode(data);
        if(index == 0) {
            addFirst(data);
            return true;
        }
        ListNode prev = head;

        while(--index > 0) {
            prev = prev.next;
        }

        ListNode cur = prev.next;
        prev.next = node;
        node.next = cur;
        return true;
    }
    // 查找上一个的节点(无法查找第一个节点)
    private static ListNode findOfPrev(ListNode start, int key) {
        if(start == null) {
            return null;
        }
        while(start.next != null) {
            if(start.next.val == key) {
                return start;
            }
            start = start.next;
        }
        return null;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        if(head == null) {
            return false;
        }
        ListNode cur = head;
        // 判断第一个是不是包含的
        if(head.val == key) {
            return true;
        }
        return findOfPrev(cur, key) != null;
    }

    //删除第一次出现关键字为key的节点
    public void remove(int key) {
        if(head == null) {
            return;
        }
        if(head.val == key) {
            head = head.next;
            return;
        }
        ListNode prev = findOfPrev(head, key);
        prev.next = prev.next.next;
    }

    //删除所有值为key的节点
    public void removeAllKey(int key) {
        if(head == null) {
            return;
        }
        while(head != null && head.val == key) {
            head = head.next;
        }

        ListNode prev = head;

        while ((prev = findOfPrev(prev, key)) != null) {
            prev.next = prev.next.next;
        }
    }

    //得到单链表的长度
    public int size() {
        int count = 0;
        ListNode cur = head;
        while(cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    public void display() {
        ListNode cur = head;
        while(cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public void clear() {
        while(head != null) {
            head = head.next;
        }
    }
}

